package solutions.leetcode.easy;

import solutions.lib.BaseSolution;

import java.util.HashSet;
import java.util.Set;

/**
 * @author lizhidong
 * <a href="https://leetcode-cn.com/problems/buddy-strings/">859. 亲密字符串</a>
 */
public class Solution859 extends BaseSolution {

    public boolean buddyStrings(String s, String goal) {
        if (s.length() != goal.length()) {
            return false;
        }
        int p = s.length() - 1;
        int checkFlag = 0;
        Character ds = null, dg = null;
        while (p >= 0) {
            char sc = s.charAt(p);
            char gc = goal.charAt(p);
            p--;
            if (sc != gc) {
                if (checkFlag == 1) {
                    return false;
                }
                if (ds == null) {
                    ds = sc;
                    dg = gc;
                    checkFlag = -1;
                } else {
                    if (gc != ds || sc != dg) {
                        return false;
                    }
                    checkFlag = 1;
                }
            }
        }
        return checkFlag == 1 || (checkFlag == 0 && hasDouble(s));
    }

    private boolean hasDouble(String s) {
        Set<Character> set = new HashSet<>();
        for (char c : s.toCharArray()) {
            if (set.contains(c)) {
                return true;
            } else {
                set.add(c);
            }
        }
        return false;
    }

    public static void main(String[] args) {
        Solution859 solution = new Solution859();
        System.out.println(solution.buddyStrings("ab", "ba"));
    }
}